package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.exception.BusinessException;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.common.util.EasyExcelImportUtils;
import com.settlement.system.model.entity.SysBaseColumnMatch;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.entity.TmOrder;
import com.settlement.system.model.form.TmOrderForm;
import com.settlement.system.model.query.TmOrderQuery;
import com.settlement.system.model.vo.TmOrderImportVo;
import com.settlement.system.service.SysBaseColumnMatchService;
import com.settlement.system.service.SysStoreService;
import com.settlement.system.service.TmOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 天猫平台订单 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-05-09
 */
@RestController
@RequestMapping("/api/v1/tmOrder")
@RequiredArgsConstructor
public class TmOrderController {

    private final TmOrderService tmOrderService;

    private final SysStoreService storeService;

    private final SysBaseColumnMatchService baseColumnMatchService;

    @GetMapping("/page")
    public PageResult<TmOrder> getPage(@ParameterObject TmOrderQuery queryParams) {
        Page<TmOrder> result = tmOrderService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存天猫平台订单", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:tmOrder:save')")
    public Result<?> saveTmOrder(@RequestBody @Valid TmOrderForm tmOrderForm) {
        boolean result = tmOrderService.saveTmOrder(tmOrderForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取天猫平台订单信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<TmOrderForm> getTmOrderFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        TmOrderForm tmOrder = tmOrderService.getTmOrderFormData(id);
        return Result.success(tmOrder);
    }

    @Operation(summary = "删除天猫平台订单", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:tmOrder:delete')")
    public Result<?> deleteTmOrder(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = tmOrderService.deleteTmOrder(ids);
        return Result.judge(result);
    }

    @Operation(summary = "天猫平台订单导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/tmOrderImport/{storeCode}")
    @PreAuthorize("@ss.hasPerm('sys:tmOrder:import')")
    @PreventDuplicateSubmit
    public Result<?> tmOrderImport(@RequestParam("file") MultipartFile file, @PathVariable("storeCode") String storeCode) {
        List<Map<String, String>> mapList = EasyExcelImportUtils.makeData(file, null, 0, 1);
        // 获取订单配置
        SysStore sysStore = storeService.getByCode(storeCode);
        List<SysBaseColumnMatch> baseColumnMatches = baseColumnMatchService.getBaseMapper().selectList(new LambdaQueryWrapper<SysBaseColumnMatch>().eq(SysBaseColumnMatch::getPlatformKey, sysStore.getStoreKey() + "order"));
        // 判断订单配置是否正确
        if (baseColumnMatches == null || baseColumnMatches.size() == 0) {
            return Result.failed("请先配置天猫平台字段对应关系");
        }
        if (baseColumnMatches.stream().filter(sysBaseColumnMatch -> SystemConstants.BUSINESS_DATE.equals(sysBaseColumnMatch.getStandardColumn())).count() != 1) {
            return Result.failed("每个平台只能允许配置一个【业务日期】的对应关系");
        }
        if (baseColumnMatches.stream().filter(sysBaseColumnMatch -> SystemConstants.PLATFORM_UNIQUE_FLAG.equals(sysBaseColumnMatch.getStandardColumn())).count() != 1) {
            return Result.failed("每个平台只能允许配置一个【唯一标识】的对应关系");
        }
        // 业务日期配置
        SysBaseColumnMatch businessConfig = baseColumnMatches.stream().filter(item -> SystemConstants.BUSINESS_DATE.equals(item.getStandardColumn())).findFirst().get();
        List<TmOrderImportVo> list = new ArrayList<>();
        TmOrderImportVo vo;
        Field declaredField;
        String billMonth;
        int rowNumber = 2;
        for (Map<String, String> stringStringMap : mapList) {
            vo = new TmOrderImportVo();
            for (String columnCn : stringStringMap.keySet()) {
                if (businessConfig.getSourceColumn().equals(columnCn)) {
                    billMonth = DateUtils.formatDate(DateUtils.convertStringToLocalDateTime(stringStringMap.get(columnCn)));
                    if (Objects.isNull(billMonth)) {
                        throw new BusinessException("第【%s】行日期格式错误：【%s】".formatted(rowNumber, stringStringMap.get(columnCn)));
                    }
                    vo.setBillMonth(billMonth);
                }
                try {
                    declaredField = vo.getClass().getDeclaredField(TmOrderImportVo.getKeyMap().get(columnCn));
                    declaredField.setAccessible(true);
                    declaredField.set(vo, stringStringMap.get(columnCn));
                } catch (Exception ignored) {
                }
            }
            rowNumber++;
            list.add(vo);
        }
        tmOrderService.importData(list, storeCode);
        return Result.success();
    }

    @Operation(summary = "导出天猫平台订单", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:tmOrder:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "天猫平台订单.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<TmOrderImportVo> tmOrderList = tmOrderService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), TmOrderImportVo.class).sheet("天猫平台订单").doWrite(tmOrderList);
    }
}

